<?php
	include "curl.php";
	switch ($_SERVER['HTTP_ORIGIN']) {
		default:
		header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
		header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
		header('Access-Control-Max-Age: 1000');
		header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		break;
	}
	if(isset($_POST['tenants_Name'])){
		
		
		$tenantToken = getTenantstoken($_POST['tenants_Name'],$_POST['token']);
		
		
		$url='http://120.96.183.123:8774/v2/56a8c118f8804b3b9925a988c210192e/limits';
			
		//開啟cURL連線
		$cURL = curl_init();

		curl_setopt($cURL, CURLOPT_URL, $url);			
		curl_setopt($cURL, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Accept: application/json',
			'X-Auth-Token:'.$tenantToken
		));			
		$result = curl_exec($cURL);
		curl_close($cURL);	
		//取得Instances
		$instance_number  = json_decode($result,true)['limits']['absolute']['totalInstancesUsed'];
		
	
		$url="http://120.96.183.123:8777/v2/meters/instance?limit=$instance_number";
		//開啟cURL連線
		$cURL = curl_init();
		curl_setopt($cURL, CURLOPT_URL, $url);			
		curl_setopt($cURL, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Accept: application/json',
			'X-Auth-Token:'.$tenantToken
		));				
		$result = curl_exec($cURL);
		curl_close($cURL);

		$result=json_decode($result,true);		
		//print_r($result);
		$instance_detail = array();		
		foreach($result as $value){
			array_push($instance_detail,array('resource_id'=>$value['resource_id'],'status'=>$value['resource_metadata']['status'],'display_name'=>$value['resource_metadata']['display_name']));
		}
		
		echo json_encode(array('tenantToken'=>$tenantToken,'instance_number'=>$instance_number,'instance_detail'=>$instance_detail));		
		

	}
	if(isset($_POST['resource_id'])){
		
		$meter=$_POST['meter'];		
		$resource_id=$_POST['resource_id'];
		$tenantToken=$_POST['tenantToken'];
		
		$url="http://120.96.183.123:8777/v2/meters/$meter?limit=1&q.field=resource_id&q.op=eq&q.value=$resource_id";		
		
		//echo '</br>'.$url.'</br>';
		
		//開啟cURL連線
		$cURL = curl_init();
		curl_setopt($cURL, CURLOPT_URL, $url);			
		curl_setopt($cURL, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Accept: application/json',
			'X-Auth-Token:'.$tenantToken,
		));				
		$ceilmeter_data = curl_exec($cURL);
		curl_close($cURL);		
		
		print_r($ceilmeter_data);
	}

?>